<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="GBK">
    <title>省市二级联动</title>
    <script src="js/jquery-3.6.0.min.js"></script>
    <script>
        //页面加载强制去请求后查询所有省份信息
        $.ajax({
            url:"city",
            data:{"method":"findAllCityByPid","pid":0},
            type:"post",
            dataType:"json",
            success:function (data) {
                console.log(data);
                //循环遍历
                $(data).each(function (index,el) {
                    //创建option选项
                    var op = '<option value="'+el.cid+'">'+el.cname+'</option>';
                    $("#province").append(op);
                })
            }
        })

        $(function () {
            $("#province").change(function () {
                //获取选中项value
                var cid = $(this).val();
                //根据cid查询
                $.ajax({
                    url:"city",
                    data:{"method":"findAllCityByPid","pid":cid},
                    type:"post",
                    dataType:"json",
                    success:function (data) {
                        $("#city").empty();
                        console.log(data);
                        //循环遍历
                        $(data).each(function (index,el) {
                            //创建option选项
                            var op = '<option value="'+el.cid+'">'+el.cname+'</option>';
                            $("#city").append(op);
                        })
                    }
                })
            })
        })
    </script>
</head>
<body>
<select id="province" name="province">

</select>
省
<select id="city" name="city">

</select>
市
</body>
</html>
